﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.Lib.IceDogSocket
{
    public class SimpleSocketServerAsync
    {
        private string ip = "127.0.0.1";
        private int port = 8800;

        IPAddress address = null;
        Socket socket = null;
        
        public SimpleSocketServerAsync()
        {
            
            address = IPAddress.Parse(ip);
            //step 1 实例化 socket 对象
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //step2 绑定ip地址和端口
            socket.Bind(new IPEndPoint(address, port));
            //step3 监听ip地址和端口
            socket.Listen(0);
            Console.WriteLine("服务端("+ip+":"+port+")进入监听状态，等待客户端连接中。。。");

            var accept = socket.Accept();
            Console.WriteLine("有客户端连接，连接已经建立");
            string recStr = "";
            byte[] recByte = new byte[4096];
            int bytes = accept.Receive(recByte, recByte.Length, 0);
            recStr += Encoding.UTF8.GetString(recByte, 0, bytes);

            Console.WriteLine("{0}", recStr);

            string sendStr = "来自服务端的消息：你好";
            byte[] sendByte = Encoding.UTF8.GetBytes(sendStr);
            accept.Send(sendByte, sendByte.Length, 0);
            accept.Close();
            Console.WriteLine("服务端accept socket关闭");
            socket.Close();
            Console.WriteLine("服务端socket关闭");
        }
    }
}
